package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.itheima.health.mapper.OrderMapper;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.service.WxPayService;
import com.itheima.health.utils.date.DateUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 *   订单添加：
 *         - 订单表  会员表  预约表 三表业务更新
 *         - 调用不同的服务，完成添加订单业务功能  @Reference  注解完成服务的调用
 */
@Service
@Transactional  // 本地事务
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {



    @Reference  //  调用 远程  服务
    private  MemberService memberService;

    @Reference
    private OrderSettingService orderSettingService;

    @Reference
    private WxPayService wxPayService;

    @Override
    @LcnTransaction
    public Order add(Map map) {
        //   重点
        String telephone = (String)map.get("telephone");
        String codeFromForm = (String)map.get("validateCode");
        String orderdate = (String)map.get("orderDate");
        String setmealId = (String)map.get("setmealId");
        Order order;
        // 1 .  验证码校验
//        String  codeFromRedis  = RedisUtil.get(RedisMessageConstant.SENDTYPE_ORDER+telephone);
//        if(StringUtils.isBlank(codeFromRedis)){
//            throw  new RuntimeException("验证码过期！");
//        }
//        if(!codeFromRedis.equals(codeFromForm)){
//            throw  new RuntimeException("验证码错误");
//        }
        //  2.  当天是否预约满   select count(1) from  t_ordersetting  where  number>reserviations and orderdate = ?
          int  count = orderSettingService.isOrderOKorNot(orderdate);
        if(count<=0){
            throw  new RuntimeException("当天预约满,择日再约！");
        }
        // 3 .  是否重复预约  -- 新会员还是老会员
       Member member =  memberService.findMemberByTelephone(telephone);
        if(member!=null){
             //  老会员    根据member_id  setmealId   orderdate  判断是否重复预约
            //  select count(1) from t_order where  mid = ? and sid = ? and orderdate = ?
            int isNotExist  = baseMapper.findOrderByMemberIDAndSetmealIDAndOrderDate(member.getId(),Integer.parseInt(setmealId),orderdate);
            if(isNotExist>0){
                throw  new RuntimeException("请勿重复预约，择日预约");
            }
            // 预约 下单
            //  添加订单记录  +  预约表 已经预约数+1
           order = generateOrder(map,member);
        }else{
            member = new Member();
           member.setRegTime(new Date(System.currentTimeMillis()));
           member.setPhoneNumber(telephone);
           member.setSex((String)map.get("sex"));
           member.setName((String)map.get("name"));
           member.setIdCard((String)map.get("idCard"));
            // 新会员信息录入 t_member表中
            int mid  = memberService.saveMember(member);  //  事务提交  主键才会诞生
            member.setId(mid);
             //  新会员  预约下单
            order = generateOrder(map,member);
        }
//        System.out.println(1/0);
        orderSettingService.updateReservationsByOrderDate(orderdate);  // update t_ordersetting set xxx=xxx+1  where  orderdate = ?
        return order;
    }

    @Override
    public Map findOrderInfoById(int id) {
        Map orderInfoById = baseMapper.findOrderInfoById(id);
        return orderInfoById;
    }

    @Override
    public Integer isPay(Integer orderNo) {
        return baseMapper.isPay(orderNo);
    }

    @Override
    public Boolean updateState(Map param) {
        String out_trade_no = (String) param.get("out_trade_no");
        String oId=out_trade_no.substring(25);
       boolean result= baseMapper.updateState(oId);
        return result;
    }

    @Override
    public void updateOrderState(String msg) {
       Integer state= baseMapper.findOrderState(Integer.valueOf(msg));
       if (state==0){
           baseMapper.deleteById(Integer.valueOf(msg));
       }
    }

    @Override
    public boolean deleteOrder(Integer id) {
        int i = baseMapper.deleteById(id);
        if (i==1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public String findTelephone(Integer orderNo) {
       String telephone= baseMapper.findTelephone(orderNo);
        return telephone;
    }

    @LcnTransaction
    private Order generateOrder(Map map, Member member) {
        String orderType = (String)map.get("orderType");
        String orderdate = (String)map.get("orderDate");
        String setmealId = (String)map.get("setmealId");
        Order order = new  Order();
        order.setMemberId(member.getId());
        order.setOrderStatus("未到诊");
        order.setOrderType(orderType);
        order.setOrderDate(DateUtils.parseString2Date(orderdate,"yyyy-MM-dd"));
        order.setSetmealId(Integer.parseInt(setmealId));
        save(order);

        return  order;
    }
}
